'use client'

import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { type Role } from '../data/schema'
import { getRouteApi, useRouter } from '@tanstack/react-router'
import { TreeSelectDropdown } from '@/components/tree-select'
import { useRoleAdd, useRoleEdit } from '@/api/roles'
import { toast } from 'sonner'
const formSchema = z
  .object({
    name: z.string().min(1, 'Username is required.'),
    pid: z.number(),
    rules: z.string().min(1, 'Role is required.'),
    isEdit: z.boolean(),
  })

type RoleForm = z.infer<typeof formSchema>

interface Props {
  currentRow?: Role
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function RolesActionDialog({ currentRow, open, onOpenChange }: Props) {
  const router = useRouter()
  const isEdit = !!currentRow
  const form = useForm<RoleForm>({
    resolver: zodResolver(formSchema),
    defaultValues: isEdit
      ? {
        ...currentRow,
        isEdit,
      }
      : {
        name: '',
        rules: '',
        pid: 0,
        isEdit,
      },
  })

  const roleAdd = useRoleAdd()
  const roleEdit = useRoleEdit()
  const onSubmit = (values: RoleForm) => {
    if (currentRow) {
      roleEdit.mutate({ ...currentRow, ...values }, {
        onSuccess: () => {
          onOpenChange(false)
          form.reset()
          router.invalidate();
          toast.success('Role Updated')
        }
      })
    } else {
      roleAdd.mutate(values, {
        onSuccess: () => {
          onOpenChange(false)
          form.reset()
          router.invalidate();
          toast.success('Role Saved')
        },
      })
    }
    // form.reset()

  }
  const routeApi = getRouteApi('/_authenticated/roles/')
  const { ruleSelect, ruleList, roleSelect, roleList } = routeApi.useLoaderData()

  return (
    <Dialog
      open={open}
      onOpenChange={(state) => {
        form.reset()
        onOpenChange(state)
      }}
    >
      <DialogContent className='sm:max-w-lg'>
        <DialogHeader className='text-left'>
          <DialogTitle>{isEdit ? 'Edit User' : 'Add New User'}</DialogTitle>
          <DialogDescription>
            {isEdit ? 'Update the user here. ' : 'Create new user here. '}
            Click save when you&apos;re done.
          </DialogDescription>
        </DialogHeader>
        <div className='-mr-4 h-[26.25rem] w-full overflow-y-auto py-1 pr-4'>
          <Form {...form}>
            <form
              id='user-form'
              onSubmit={form.handleSubmit(onSubmit)}
              className='space-y-4 p-0.5'
            >
              <FormField
                control={form.control}
                name='pid'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Parent Role
                    </FormLabel>
                    <TreeSelectDropdown
                      defaultValue={field.value?.toString()}
                      onValueChange={(value) => field.onChange(parseInt(value))}
                      placeholder='Select rules'
                      className='col-span-4 text-muted-foreground'
                      treeItems={roleSelect}
                      listItems={roleList}
                      enableSubSelection={false}
                      enableMultiRowSelection={false}
                    />
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='name'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Role name
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder='john_doe'
                        className='col-span-4'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name='rules'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Rule
                    </FormLabel>
                    <TreeSelectDropdown
                      defaultValue={field.value}
                      onValueChange={field.onChange}
                      placeholder='Select rules'
                      className='col-span-4 text-muted-foreground'
                      treeItems={ruleSelect}
                      listItems={ruleList}
                    />
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />

            </form>
          </Form>
        </div>
        <DialogFooter>
          <Button type='submit' form='user-form'>
            Save changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
